package imdservice.thread;

import imdservice.net.SocketClientManager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.net.UnknownHostException;


/**
 * 
 * @author 20082755
 *
 */
public class UploadThread implements Runnable{

	private Socket socket;
	private File file;

	public final static int BUFFER = 40960*2;
	private boolean isPause;
	private String mIp;
	
	public UploadThread(String mIp) {
		this.file = file;
		this.mIp = mIp;
		file = new File("D:\\Android\\app-release.apk");
		System.out.print("文件：" + file.getAbsolutePath());
		try {
			//TODO: 获取指定IP的Socket
			socket = SocketClientManager.getSocket(mIp,8626);
			System.out.println("Socket Service: " + "移动服务器");
			System.out.println("Socket Address: " + socket.getInetAddress());
			System.out.println("Socket Port: " + socket.getLocalPort());
			System.out.println("Socket Service: " + "本地客户端");
			System.out.println("Socket Port: " + socket.getLocalSocketAddress());
			System.out.println("Socket LockPort: " + socket.getLocalPort());
			System.out.println("Socket KeepAlive: " + socket.getKeepAlive());
			System.out.println("Socket Channel: " + socket.getChannel());
			System.out.println("开始上传文件......");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
			//得到输出流
			DataOutputStream out = new DataOutputStream(socket.getOutputStream());
			byte[] buffer = new byte[BUFFER];
			int len = -1;
			long length = 0;
			while (!isPause&&(len = randomAccessFile.read(buffer)) != -1) {
				out.write(buffer, 0, len);
				out.flush();
				length += len;
				System.out.println("已上传：" + (length*100)/file.length() + "%");
			}
			randomAccessFile.close();
			out.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
		}
	}
	public void setPause(boolean isPause) {
		this.isPause = isPause;
	}
	
}
